<!--观察者模式：客户端和服务端解耦-->
<html>
<style>
div{
	margin:10px;
	width:500px;
	height:200px;
	border: 1px solid green;
}
</style>
<head>

</head>
<body>
	<h1>观察者模式</h1>
	<select id="select" >
		<option value="man">男士风格</option>
		<option value="woman">女士风格</option>
	</select>
	<input type="button" value="观察尾部模块" onclick="observe()"/>
	<input type="button" value="不观察尾部模块" onclick="notobserve()"/>
	<div id="content">我是内容</div>
	<div id="ad">我是广告</div>
	<div id="study">我是学习</div>

</body>

<script>
		var sel = document.getElementById('select');
		sel.styles = {};
		sel.attach = function(key,obj){
			sel.styles[key] = obj;
		}
		sel.detach = function(key){
			delete sel.styles[key];
		}

		sel.onchange = sel.notify = function(){
			for(var key in this.styles){
				this.styles[key].update(this);
			}
		}

		//客户端
		var content = document.getElementById('content');
		content.update = function(styles){
			if(styles.value == 'man'){
				this.style.backgroundColor = 'gray';
			}else{
				this.style.backgroundColor = 'pink';
			}
		}
		sel.attach('content',content);//监听

		var ad = document.getElementById('ad');
		ad.update = function(styles){
			if(styles.value == 'man'){
				this.innerHTML = '汽车';
			}else{
				this.innerHTML = '减肥';
			}
		}
		sel.attach('ad',ad);//监听

		var study = document.getElementById('study');
		study.update = function(styles){
			if(styles.value == 'man'){
				this.innerHTML = '学习计算机';
			}else{
				this.innerHTML = '学习美容';
			}
		}

		//观测按钮
		function observe(){
			sel.attach('study',study);//监听
		}

		function notobserve(){
			sel.detach('study');//取消监听
		}


	</script>	








</html>	
